package com.wosai.register.util;

import java.io.UnsupportedEncodingException;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.codec.Base64;


public class SecurityUtil {
    
    public static String encodeToken(String username, String password) {
        try {
            return new String(Base64.encode((username+":"+password).getBytes("UTF-8")), "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static String[] decodeToken(String token) {
        try {
            byte[] base64Token = token.getBytes("UTF-8");
            byte[] decoded = Base64.decode(base64Token);
            String delimited = new String(decoded, "UTF-8");
            String[] fields = delimited.split(":");
            return fields;
        }
        catch (UnsupportedEncodingException e) {
            return null;
        }
    }
    
    private static Md5PasswordEncoder _encoder = new Md5PasswordEncoder();
    public static String encodePassword(String password){
        //return _encoder.encodePassword(password, null);
        return PwdEncrptor.getCipher(password);
    }
    
    
    public static String getCurrentUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            return ((UserDetails)principal).getUsername();
        } else {
            return (String)principal;
        }
    }

}
